import React, { useState } from 'react';
import {
  Card,
  Form,
  Row,
  Col,
  Input,
  Select,
  Slider,
  Switch,
  Button,
  Space,
  Typography,
  Divider,
  message,
  Modal,
  List,
} from 'antd';
import {
  SearchOutlined,
  SaveOutlined,
  HistoryOutlined,
  FilterOutlined,
  ClearOutlined,
} from '@ant-design/icons';
import { SearchFilters } from '@/types';
import { useNavigate } from 'react-router-dom';

const { Title, Text } = Typography;
const { Option } = Select;

const AdvancedSearch: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [saveConditionModalVisible, setSaveConditionModalVisible] = useState(false);
  const [searchHistoryVisible, setSearchHistoryVisible] = useState(false);
  const [savedConditions, setSavedConditions] = useState<any[]>([]);
  const [searchHistory, setSearchHistory] = useState<any[]>([]);

  // Mock data
  const cities = ['北京', '上海', '广州', '深圳', '杭州', '南京', '成都', '武汉', '西安', '重庆'];
  const educations = ['高中', '大专', '本科', '硕士', '博士'];
  const occupations = ['设计师', '工程师', '教师', '医生', '律师', '销售', '运营', '产品经理'];
  const interests = ['旅行', '美食', '运动', '读书', '电影', '音乐', '摄影', '健身', '瑜伽', '游戏'];

  const handleSearch = async (values: SearchFilters) => {
    try {
      setLoading(true);
      
      // Add to search history
      const historyItem = {
        id: Date.now().toString(),
        conditions: values,
        timestamp: new Date().toISOString(),
        resultCount: Math.floor(Math.random() * 50) + 10,
      };
      setSearchHistory(prev => [historyItem, ...prev.slice(0, 9)]);
      
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      message.success(`找到 ${historyItem.resultCount} 个匹配结果`);
      
      // Navigate to results
      navigate('/search/result', { state: { filters: values, resultCount: historyItem.resultCount } });
    } catch (error) {
      message.error('搜索失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSaveCondition = async (conditionName: string) => {
    try {
      const values = await form.validateFields();
      const savedCondition = {
        id: Date.now().toString(),
        name: conditionName,
        conditions: values,
        createTime: new Date().toISOString(),
      };
      
      setSavedConditions(prev => [savedCondition, ...prev]);
      message.success('搜索条件已保存');
      setSaveConditionModalVisible(false);
    } catch (error) {
      message.error('保存失败');
    }
  };

  const handleLoadCondition = (condition: any) => {
    form.setFieldsValue(condition.conditions);
    message.success('已加载搜索条件');
    setSearchHistoryVisible(false);
  };

  const handleReset = () => {
    form.resetFields();
  };

  return (
    <div className="page-container">
      <div className="page-header">
        <Title level={4} className="page-title">高级搜索</Title>
        <Text className="page-description">
          多维度筛选条件，快速找到符合要求的用户
        </Text>
      </div>

      <Row gutter={[24, 24]}>
        {/* Search Form */}
        <Col xs={24} lg={16}>
          <Card
            title={
              <Space>
                <FilterOutlined />
                搜索条件
              </Space>
            }
            extra={
              <Space>
                <Button
                  icon={<HistoryOutlined />}
                  onClick={() => setSearchHistoryVisible(true)}
                >
                  历史搜索
                </Button>
                <Button
                  icon={<SaveOutlined />}
                  onClick={() => setSaveConditionModalVisible(true)}
                >
                  保存条件
                </Button>
              </Space>
            }
          >
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSearch}
              initialValues={{
                ageRange: [22, 35],
                heightRange: [155, 185],
                incomeRange: [5000, 50000],
                isVip: false,
              }}
            >
              <Row gutter={[24, 16]}>
                {/* Basic Info */}
                <Col span={24}>
                  <Title level={5}>基础信息</Title>
                </Col>
                
                <Col xs={24} sm={12} md={8}>
                  <Form.Item label="性别" name="gender">
                    <Select placeholder="选择性别" allowClear>
                      <Option value="male">男</Option>
                      <Option value="female">女</Option>
                    </Select>
                  </Form.Item>
                </Col>
                
                <Col xs={24} sm={12} md={8}>
                  <Form.Item label="年龄范围" name="ageRange">
                    <Slider
                      range
                      min={18}
                      max={60}
                      marks={{
                        18: '18',
                        30: '30',
                        45: '45',
                        60: '60'
                      }}
                    />
                  </Form.Item>
                </Col>
                
                <Col xs={24} sm={12} md={8}>
                  <Form.Item label="身高范围(cm)" name="heightRange">
                    <Slider
                      range
                      min={150}
                      max={200}
                      marks={{
                        150: '150',
                        170: '170',
                        185: '185',
                        200: '200'
                      }}
                    />
                  </Form.Item>
                </Col>

                {/* Social Info */}
                <Col span={24}>
                  <Divider />
                  <Title level={5}>社会属性</Title>
                </Col>
                
                <Col xs={24} sm={12} md={8}>
                  <Form.Item label="学历" name="education">
                    <Select placeholder="选择学历" allowClear>
                      {educations.map(edu => (
                        <Option key={edu} value={edu}>{edu}</Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
                
                <Col xs={24} sm={12} md={8}>
                  <Form.Item label="职业" name="occupation">
                    <Select placeholder="选择职业" allowClear>
                      {occupations.map(occ => (
                        <Option key={occ} value={occ}>{occ}</Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
                
                <Col xs={24} sm={12} md={8}>
                  <Form.Item label="收入范围(元/月)" name="incomeRange">
                    <Slider
                      range
                      min={0}
                      max={100000}
                      step={1000}
                      marks={{
                        0: '0',
                        20000: '2w',
                        50000: '5w',
                        100000: '10w+'
                      }}
                    />
                  </Form.Item>
                </Col>

                {/* Location */}
                <Col span={24}>
                  <Divider />
                  <Title level={5}>地理位置</Title>
                </Col>
                
                <Col xs={24} sm={12} md={8}>
                  <Form.Item label="所在城市" name={['location', 'city']}>
                    <Select placeholder="选择城市" allowClear showSearch>
                      {cities.map(city => (
                        <Option key={city} value={city}>{city}</Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
                
                <Col xs={24} sm={12} md={8}>
                  <Form.Item label="周边距离(km)" name={['location', 'radius']}>
                    <Select placeholder="选择距离" allowClear>
                      <Option value={5}>5公里内</Option>
                      <Option value={10}>10公里内</Option>
                      <Option value={20}>20公里内</Option>
                      <Option value={50}>50公里内</Option>
                      <Option value={100}>不限</Option>
                    </Select>
                  </Form.Item>
                </Col>

                {/* Interests */}
                <Col span={24}>
                  <Divider />
                  <Title level={5}>兴趣爱好</Title>
                </Col>
                
                <Col span={24}>
                  <Form.Item label="兴趣标签" name="tags">
                    <Select
                      mode="multiple"
                      placeholder="选择兴趣标签"
                      allowClear
                      maxTagCount={5}
                    >
                      {interests.map(interest => (
                        <Option key={interest} value={interest}>{interest}</Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>

                {/* Additional Options */}
                <Col span={24}>
                  <Divider />
                  <Title level={5}>其他选项</Title>
                </Col>
                
                <Col xs={24} sm={12}>
                  <Form.Item label="只显示VIP用户" name="isVip" valuePropName="checked">
                    <Switch />
                  </Form.Item>
                </Col>
                
                <Col xs={24} sm={12}>
                  <Form.Item label="有照片的用户" name="hasPhotos" valuePropName="checked">
                    <Switch />
                  </Form.Item>
                </Col>

                {/* Action Buttons */}
                <Col span={24}>
                  <Divider />
                  <Space size="large">
                    <Button
                      type="primary"
                      size="large"
                      icon={<SearchOutlined />}
                      htmlType="submit"
                      loading={loading}
                    >
                      开始搜索
                    </Button>
                    <Button
                      size="large"
                      icon={<ClearOutlined />}
                      onClick={handleReset}
                    >
                      清空条件
                    </Button>
                  </Space>
                </Col>
              </Row>
            </Form>
          </Card>
        </Col>

        {/* Quick Search & Saved Conditions */}
        <Col xs={24} lg={8}>
          <Card title="快捷搜索" style={{ marginBottom: '16px' }}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <Button
                block
                onClick={() => {
                  form.setFieldsValue({
                    gender: 'female',
                    ageRange: [25, 35],
                    education: '本科',
                    location: { city: '北京' },
                  });
                }}
              >
                北京本科女性 25-35岁
              </Button>
              <Button
                block
                onClick={() => {
                  form.setFieldsValue({
                    gender: 'male',
                    ageRange: [28, 40],
                    education: '硕士',
                    incomeRange: [15000, 50000],
                  });
                }}
              >
                高学历男性 28-40岁
              </Button>
              <Button
                block
                onClick={() => {
                  form.setFieldsValue({
                    isVip: true,
                    hasPhotos: true,
                    tags: ['旅行', '美食'],
                  });
                }}
              >
                VIP用户 + 旅行美食爱好
              </Button>
            </Space>
          </Card>

          {savedConditions.length > 0 && (
            <Card title="已保存条件">
              <List
                size="small"
                dataSource={savedConditions}
                renderItem={(item) => (
                  <List.Item
                    actions={[
                      <Button
                        key="load"
                        type="link"
                        size="small"
                        onClick={() => handleLoadCondition(item)}
                      >
                        加载
                      </Button>,
                    ]}
                  >
                    <div>
                      <Text strong>{item.name}</Text>
                      <br />
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        {new Date(item.createTime).toLocaleDateString()}
                      </Text>
                    </div>
                  </List.Item>
                )}
              />
            </Card>
          )}
        </Col>
      </Row>

      {/* Modals */}
      <Modal
        title="保存搜索条件"
        open={saveConditionModalVisible}
        onCancel={() => setSaveConditionModalVisible(false)}
        footer={null}
      >
        <Form onFinish={(values) => handleSaveCondition(values.name)}>
          <Form.Item
            label="条件名称"
            name="name"
            rules={[{ required: true, message: '请输入条件名称' }]}
          >
            <Input placeholder="为这个搜索条件起个名字" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button onClick={() => setSaveConditionModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="搜索历史"
        open={searchHistoryVisible}
        onCancel={() => setSearchHistoryVisible(false)}
        footer={null}
        width={600}
      >
        <List
          dataSource={searchHistory}
          renderItem={(item) => (
            <List.Item
              actions={[
                <Button
                  key="load"
                  type="link"
                  onClick={() => handleLoadCondition(item)}
                >
                  重新搜索
                </Button>,
              ]}
            >
              <List.Item.Meta
                title={
                  <Space>
                    <Text>搜索结果: {item.resultCount} 人</Text>
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                      {new Date(item.timestamp).toLocaleString()}
                    </Text>
                  </Space>
                }
                description={
                  <div>
                    {item.conditions.gender && (
                      <span style={{ marginRight: '8px' }}>
                        性别: {item.conditions.gender === 'male' ? '男' : '女'}
                      </span>
                    )}
                    {item.conditions.ageRange && (
                      <span style={{ marginRight: '8px' }}>
                        年龄: {item.conditions.ageRange[0]}-{item.conditions.ageRange[1]}岁
                      </span>
                    )}
                  </div>
                }
              />
            </List.Item>
          )}
        />
      </Modal>
    </div>
  );
};

export default AdvancedSearch;